<template>
  <el-container> 
    <el-header id="Header">
      <el-row id="Control" :gutter="10">
        <!--过滤参数选择-->
        <el-col :span="6">
          <span id="FilterParameters">过滤参数：</span>
          <el-select id="FilterBox" v-model="FilterParameter_value" placeholder="请选择" title="过滤参数:">
            <el-option
              v-for="item in FilterParameters"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <!--查找输入框-->
        <el-col :span="1">
          <span id="Value">值：</span>
        </el-col>
        <el-col :span="4">
          <el-input v-model="CompleteValue" placeholder="请输入内容" />
        </el-col>
        <!--查找、新增功能按钮-->
        <el-col :span="13">
          <el-button id="Find" type="primary" @click=" Find()">过滤</el-button>
          <el-button type="primary" @click="dealData()">取消过滤</el-button>
          <el-button id="Add" type="success" @click="dialogAddVisible = true, getAllServerId()">新增</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-main id="Main" :style="myStyle">
      <el-table
        :data="tableData"
        height="100%"
        border
        style="width: 87.8rem"
        :cell-class-name="tableCellClassName"
        @cell-mouse-enter="getNowRow"
        @row-dblclick="gotoDetails"
      >
        <!--序号-->
        <el-table-column
          width="50"
          type="index"
          label="序号"
        />
        <!--超市id：serverId-->
        <el-table-column
          prop="id"
          label="超市ID"
        />
        <!--超市名称（服务器：serverName-->
        <el-table-column
          prop="name"
          label="超市名称"
        />
        <!--服务器ip：serverIp-->
        <el-table-column
          prop="serverIp"
          label="服务器IP"
        />
        <!--服务器运维管理端口：serverPort-->
        <el-table-column
          prop="address"
          label="超市地址"
        />
        <!--是否监测该服务器：monitored-->
        <el-table-column
          prop="monitored"
          label="绑定用户"
        />
        <!--是否控制该服务器：controlled-->
        <el-table-column
          prop="createTime"
          label="创建时间"
        />
        <!--操作栏-->
        <el-table-column
          label="操作"
          width="330"
        >
          <template slot-scope="scope">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-button type="primary" @click="dialogEquipmentVisible = true, tableEquipmentVisible = true, getProbe(scope.row)">设备</el-button>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="dialogCustomerVisible = true, tableCustomerVisible = true, getCustomer(scope.row)">用户</el-button>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="dialogReviseVisible = true, ReviseServer(scope.row)">修改</el-button>
              </el-col>
              <el-col :span="6">
                <el-button type="danger" @click="Del(scope.row.id)">删除</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer id="Footer">
      <el-row :gutter="30">
        <el-col :span="10">
          <div id="now_line_number">第 {{ nowRow }} 条/共 {{ totalNumber }} 条数据</div>
        </el-col>
        <el-col :span="14">
          <div>
            <el-pagination
              id="controlBigPosition"
              background
              :current-page="currentPage"
              :page-sizes="[20, 50, 100, 200, 300]"
              :page-size="size"
              layout="sizes, prev, pager, next, jumper"
              :total="totalNumber"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-button id="controlPosition" type="primary" round>跳转</el-button>
          </div>
        </el-col>
      </el-row>
    </el-footer>

    <!--新增按钮的弹窗-->
    <el-dialog top="16vh" title="新增超市信息" :visible.sync="dialogAddVisible" width="30%">
      <el-form ref="addForm" :model="addForm" label-width="100px">
        <!--超市名称-->
        <el-form-item label="超市名称">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <!--地址-->
        <el-form-item label="地址">
          <el-input v-model="addForm.address" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogAddVisible = false, add()">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改按钮的弹窗-->
    <el-dialog top="20vh" title="修改区域信息" :visible.sync="dialogReviseVisible" width="30%">
      <el-form ref="reviseForm" :model="reviseForm" label-width="100px">
        <!--服务器id-->
        <!--超市名称-->
        <el-form-item label="超市名称">
          <el-input v-model="reviseForm.name" />
        </el-form-item>
        <!--地址-->
        <el-form-item label="地址">
          <el-input v-model="reviseForm.address" />
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogReviseVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogReviseVisible = false, ReviseServerConfirm()">确 定</el-button>
      </span>

    </el-dialog>

    <!--设备按钮的弹窗-->
    <el-dialog top="20vh" title="相关设备信息" :visible.sync="dialogEquipmentVisible" width="40%">
      <el-table
        :data="EquipmentTableData"
        height="44vh"
        border
        style="width: 87.8rem"
        :cell-class-name="tableCellClassName"
        @cell-mouse-enter="getNowRow"
        @row-dblclick="gotoDetails"
      >
        <!--序号-->
        <el-table-column
          width="50"
          type="index"
          label="序号"
        />
        <el-table-column
          prop="id"
          label="设备ID"
        />
        <!--设备名称（服务器：serverName-->
        <el-table-column
          prop="guid"
          label="设备序列号"
        />
        <!--是否监测该服务器：monitored-->
        <el-table-column
          prop="status"
          :formatter="dealStatus"
          label="状态"
        />
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-row :gutter="12">
              <el-col>
                <el-button type="primary" @click="delProbe(scope.row.id)">解绑</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="tableEquipmentVisible" id="targetTable">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-tooltip class="item" effect="dark" content="输入设备ID/序列号进行查询" placement="top">
              <el-input v-model="ProbeForm.searchProbeKeyword" placeholder="查询输入" />
            </el-tooltip>
          </el-col>
        </el-row>
        <el-table
          :data="ProbeForm.searchProbeInfos"
          height="500"
          border
          style="width: 100%"
        >
          <el-table-column
            prop="id"
            label="设备ID"
          />
          <el-table-column
            prop="guid"
            label="设备序列号"
          />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="targetTableGetFocus(scope.$index, scope.row)">绑定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!--客户按钮的弹窗-->
    <el-dialog top="20vh" title="相关客户信息" :visible.sync="dialogCustomerVisible" width="50%">
      <el-table
        :data="CustomerTableData"
        height="44vh"
        border
        style="width: 87.8rem"
        :cell-class-name="tableCellClassName"
        @cell-mouse-enter="getNowRow"
        @row-dblclick="gotoDetails"
      >
        <!--序号-->
        <el-table-column
          width="50"
          type="index"
          label="序号"
        />
        <!--用户名：userId-->
        <el-table-column
          prop="name"
          label="用户名称"
        />
        <!--超市名称（服务器：serverName-->
        <el-table-column
          prop="userName"
          label="登录名称"
        />
        <!--绑定用户数量-->
        <el-table-column
          prop="phone"
          label="电话"
        />
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-row :gutter="12">
              <el-col>
                <el-button type="primary" @click="delUser(scope.row.id)">解绑</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="tableCustomerVisible" id="targetTable">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-tooltip class="item" effect="dark" content="输入名称进行查询" placement="top">
              <el-input v-model="UserForm.searchUserKeyword" placeholder="查询输入" />
            </el-tooltip>
          </el-col>
        </el-row>
        <el-table
          :data="UserForm.allUserInfos"
          height="500"
          border
          style="width: 100%"
        >
          <el-table-column
            prop="id"
            label="客户ID"
          />
          <el-table-column
            prop="name"
            label="客户名称"  
          />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="targetTableGetFocus(scope.$index, scope.row)"
              >绑定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-dialog>

  </el-container>
</template>

<script>
import { myLogin } from '@/api/erea'
import { DelProbe } from '@/api/probeManager.js'
import {
  getAllAreas, searchAreaById, searchAreaByName,
  addArea, delArea, getUserOfArea, getProbeByAreaId,
  getAllProbe, deleteProbe
} from '@/api/areaManager.js'
import { DelUser, getAllUser } from '@/api/userManager.js'

export default {
  name: 'Area',
  data() {
    return {
      customerIdTable: [],
      //* ******************控制区*******************
      // 过滤参数下拉框
      FilterParameters: [
        {
          value: 'name',
          label: '超市名称'
        }, {
          value: 'areaId',
          label: '超市Id'
        }
      ],
      // 过滤参数的值
      FilterParameter_value: '',
      // 查找输入框
      CompleteValue: '',
      //* ******************中间主体*******************
      controlWidth: {
        width: '100%'
      },
      // 处理页面自适应
      myStyle: {
        height: '29rem'
      },
      // 表格数据
      tableData: [],
      CustomerTableData: [],
      allTableData: [],
      areaId: '',

      // 设备绑定表单
      ProbeForm: {
        searchProbeKeyword: '',
        searchProbeInfos: [],
        allProbeInfos: []
      },

      //* ******************分页尾部*******************
      // 分页
      // currentPage进入的第一页是第几页
      currentPage: 1,
      pageSize: 20,
      // 当前行数
      nowRow: 1,
      // 数据总数
      totalNumber: '',
      // 当前页面显示最大数量
      size: 20,

      //* ******************弹窗*******************
      // 新增弹窗
      tableCustomerIdVisible: false,
      dialogAddVisible: false,
      addForm: {
        name: '',
        address: ''
      },
      CustomerIdTable: [],
      BackupCustomerIdTable: [],

      // 修改的弹窗
      dialogReviseVisible: false,
      reviseForm: {
        name: '',
        address: ''
      },

      // 设备的弹窗
      nowRowId: '',
      dialogEquipmentVisible: false,
      tableEquipmentVisible: false,
      CustomerForm: {},
      BackupCustomerForm: {},
      nowServerId: '',
      EquipmentTableData: [],
      // 用户绑定表单
      UserForm: {
        searchUserKeyword: '',
        searchUserInfos: [],
        allUserInfos: []
      },
      // 客户的弹窗
      dialogCustomerVisible: false,
      tableCustomerVisible: true,
      // CustomerForm: {},
      // BackupCustomerForm: {},
      // nowServerId: '',
      CustomerTableCompleteValue: '',
      allCustomerTable: [],
      searchCustomerTable: []

      
    }
  },
  watch: {
    // 当对应指标中输入东西的时候搜索
    // 'RegionForm.searchRegionKeyword': {
    //   immediate: true,
    //   handler(val){
    //     this.RegionForm.searchRegionInfos = this.RegionForm.allRegionInfos.filter(p => {
    //       return p.name.indexOf(val) !== -1
    //     })
    //   }
    // },
    // 用户过滤
    'UserForm.searchUserKeyword': {
      immediate: true,
      handler(val) {
        this.UserForm.searchUserInfos = this.UserForm.allUserInfos.filter(p => {
          return p.name.indexOf(val) !== -1
        })
      }
    },
    'ProbeForm.searchProbeKeyword': {
      immediate: true,
      handler(val) {
        this.ProbeForm.searchProbeInfos = this.ProbeForm.allProbeInfos.filter(p => {
          // console.log(this.ProbeForm.searchProbeInfos);
          // console.log(this.ProbeForm.allProbeInfos);
          return p.guid.indexOf(val) !== -1
        })
      }
    }
  },
  mounted() {
    // 获取所有区域信息
    getAllAreas(this.currentPage, this.pageSize).then(request => {
      // console.log('res', request)a
      this.tableData = request.data.records
      this.totalNumber = request.data.total
    })
    //获取所有用户信息
    getAllUser(1, 99999).then(request => {
      console.log('allUser',request)
      this.UserForm.allUserInfos = request.data.records,
      this.UserForm.searchUserTable = request.data.records
    })
    // 获取所有设备信息
    getAllProbe(1, 99999).then(request => {
      console.log('allProbe', request)
      this.ProbeForm.allProbeInfos = request.data.records
      this.ProbeForm.searchProbeInfos = request.data.records
    })
    myLogin('', '12345', 'hq', '0').then(request => {
    })
    // this.dealData()
    this.myStyle = {
      height: document.body.clientHeight - 50 - 30 - 64 - 70 + 'px'
    }
    // 获取所有用户信息

  },
  methods: {
    // 添加区域
    add() {
      const addTmpTable = {
        'address': this.addForm.address,
        'createTime': '',
        'creatorId': 0,
        'id': 0,
        'name': this.addForm.name
      }
      addArea(addTmpTable).then(request => {
        console.log('addres', request)
        if (request.success) {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.Find()
        } else {
          this.$message({
            message: request.data,
            type: 'warning'
          })
        }
      })
    },
    //* *********************数据更新**********************
    dealData() {
      getAllAreas(this.currentPage, this.pageSize).then(request => {
        console.log('res', request)
        this.tableData = request.data.records
        this.totalNumber = request.data.total
      })
      this.FilterParameter_value = ''
      this.CompleteValue = ''
    },
    // 获取区域下用户信息
    getCustomer(row) {
      this.areaId = row.id
      // 获取区域下的用户
      getUserOfArea( this.areaId,this.currentPage, this.pageSize).then(request => {
        this.CustomerTableData = request.data.records
      })
    },
    // 获取区域下的设备
    getProbe(row) {
      this.nowRowId = row.id
      getProbeByAreaId(row.id, this.currentPage, this.pageSize).then(request => {
        this.EquipmentTableData = request.data.records
      })
    },
    // 删除设备
    delProbe(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DelProbe(id).then(request => {
          if (request.success) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            console.log('delnowRowId', this.nowRowId)
            getProbeByAreaId(this.nowRowId, this.currentPage, this.pageSize).then(request => {
              console.log('probeById: ', request)
              this.EquipmentTableData = request.data.records
            })
          } else {
            this.$message({
              message: request.data,
              type: 'warning'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    delUser(id) {
      // console.log('row:',row);
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DelUser(id).then(request => {
          if (request.success) {
            this.dealData()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            getUserOfArea(this.nowRowId, this.currentPage, this.pageSize).then(request => {
              console.log('probeById: ', request)
              this.CustomerTableData = request.data.records
            })
          } else {
            super.$message({
              message: request.data,
              type: 'warning'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    Find() {
      if (this.FilterParameter_value === 'name') {
        searchAreaByName(this.CompleteValue).then(request => {
          this.tableData = request.data
        })
      } else if (this.FilterParameter_value === 'areaId') {
        searchAreaById(this.CompleteValue, this.currentPage, this.pageSize).then(request => {
          this.tableData = request.data.records
        })
      } else {
        this.dealData()
      }
    },
    //* ***********************分页************************
    // 鼠标放到某一行上就触发
    tableCellClassName({ row, rowIndex }) {
      row.index = rowIndex
    },
    // 鼠标放到某一行上就触发
    getNowRow(row) {
      this.nowRow = row.index + 1 + (this.currentPage - 1) * this.size
    },
    // 鼠标双击某行触发
    gotoDetails(row) {
      this.$router.push({ name: 'Details', params: { row: row }})
    },
    // 每页最大条数
    handleSizeChange(val) {
      this.size = val
      this.currentPage = 1
      this.Find()
    },
    // 当前页数
    handleCurrentChange(val) {
      this.currentPage = val
      this.Find()
    },
    //* *********************表格主体**********************
    // 为修改表单获取当前行的值
    ReviseServer(row) {
      const target = {}
      Object.assign(target, row)
      this.reviseForm = target
      this.reviseForm.monitored = this.reviseForm.monitored.toString()
      this.reviseForm.controlled = this.reviseForm.controlled.toString()
    },
    // 确认修改
    ReviseServerConfirm() {
      getOpServerUpdate(this.reviseForm).then(request => {
        if (request.data.body) {
          this.Find()
          this.$message({
            type: 'success',
            message: '更新成功'
          })
        } else {
          this.$message({
            message: request.data.msg,
            type: 'warning'
          })
        }
      })
    },
    ReviseCustomer() {
      if (this.BackupCustomerForm.customerId && this.nowServerId) {
        getOpCustomerServerDelete(this.BackupCustomerForm.customerId, this.nowServerId).then(request => {})
      }
      this.CustomerForm.serverId = this.nowServerId
      getOpCustomerServerCreate(this.CustomerForm).then(request => {
        if (request.data.body) {
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
        } else {
          this.$message({
            message: request.data.msg,
            type: 'warning'
          })
        }
      })
    },

    // 服务器状态判断
    dealStatus(row) {
      if (row.status === 0) {
        return '关'
      }
      if (row.status === 1) {
        return '开'
      }
    },
    //* ***********************弹窗************************
    // 删除功能的事件
    Del(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delArea(id).then(request => {
          if (request.success) {
            this.Find()
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message({
              message: request.data,
              type: 'warning'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    targetTableIdGetFocus(row) {
      this.addForm.customerId = row.customerId
    },
    // 添加客户id
    targetTableGetFocus(index, row) {
      this.CustomerForm.customerId = row.customerId
      this.CustomerTableCompleteValue = this.CustomerForm.customerId
    }
  }
}
</script>

<style scoped>

>>>.el-table__body-wrapper .el-table__row .el-table__cell{
  padding-top: 4px;
  padding-bottom: 4px;
}
#Header{
  background: #f1f3f4;
}
#Find{
  margin-left: 1rem;
}
#Control{
  margin-top: 0.8rem;
}
.dialog-footer{
  margin: 0 auto;
}
#targetTable{
  position: absolute;
  top: 0;
  left:103%;
}
#targetIdTable{
  position: absolute;
  top: 1%;
  left:103%;
}
/*设置分页属性*/
#now_line_number{
  font-size: 0.85rem;
  margin-left: 2rem;
  margin-top: 0.6rem;
  color: #606266;
  float:left;
}
#paginate{
  float:right;
  margin-right: 2rem;
}
#Value{
  line-height: 2.2rem;
  padding-left: 1.2rem;
}
#myFooter{
  position: absolute;
  right: 4vh;
  bottom: 2vh;
}
#controlPosition{
  display: inline-block;
  position: absolute;
  right: 2rem;
  top: 0;
}
#controlBigPosition{
  position: absolute;
  right: 7.2rem;
}
#controlBigPosition{
  position: absolute;
  right: 7.2rem;
}
#controlPosition{
  display: inline-block;
  position: absolute;
  right: 2rem;
  top: 0;
}
</style>
